	export default {
		name: "zjdr",
		props: {
    		bgsx: {
                type: Object,
                default: () => ({})
    		},
		},
		
		setup(props, {emit}) {
			const tempjson = ref([]);
			const pageState = ref({total: 0,percent: 0, page: 1,pageSize: 10});
			const fieldsConfig = ref({});
			const upload = ref(null);
			const newbgsx = ref({...props.bgsx});
            const drjy = ref(false); //导入校验
            const qdloading = ref(false); //确定按钮状态
            const singleTable = ref(null);
            
            watch(() => props.bgsx,(newVal) => {newbgsx.value = { ...newVal };},{ deep: true })
            
            //重置数据
			const resetUploadState = () => {
				pageState.value = {total: 0,percent: 0, page: 1,pageSize: 10};
				tempjson.value = [];
			};

			const handleFileChange = async (file) => {
				try {
					resetUploadState();
					const validFile = getValidFile(file);
					const jsonData = await readExcelFile(validFile);
					console.log('数据处理完成')
					await processImportedData(jsonData);
					newbgsx.value.fields = fieldsConfig.value;
					newbgsx.value.kfcx = Object.keys(newbgsx.value.fields);
					newbgsx.value.cxtj = [];
				} catch (error) {
					console.error(' 文件处理失败:', error);
    				ElMessage.error(error.message);
				}
			};

			const processImportedData = (jsonData) => {
				if (!jsonData?.length) throw new Error('表格数据为空');
				fieldsConfig.value = {};
				const sampleRow = jsonData[0];
				Object.keys(sampleRow).forEach((key, index) => {
					const fieldKey = `K${index + 1}`;
					const sampleValue = sampleRow[key];
					// 类型检测，自动判断是否图片
                    let fieldType = "text";
                    let placeholder = `请输入${key}`;
                    if (typeof sampleValue === 'string') {
                        if (window.validators.isImageUrl(sampleValue)) {
                            fieldType = "image";
                            placeholder = `请上传${key}`
                        }
                    }
                    fieldsConfig.value[fieldKey] = {
						type: fieldType,
						name: key,
						placeholder: placeholder,
						required: false
					};
				});
				tempjson.value = jsonData.filter(row =>
					Object.values(row).some(v => v !== null && v !== undefined && v !== '')
				);
				pageState.value.total = tempjson.value.length;
			};

            const beforeUpload = (file) => {
                const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                const isXlsx = file.name.endsWith('.xlsx');
                if (!isExcel || !isXlsx) {
                    ElMessage.error('只能上传.xlsx格式的Excel文件!');
                    return false;
                }
                return true;
            };
            
            //提交前基础校验
            const submitDrsj = () => {
                if(qdloading.value || pageState.value.total < 1) {
                    return ElMessage.error('表格内容为空');
                }else{
                    //校验字段是否和原表一致
            		let t = {};
            		for (const k in props.bgsx.fields) {
            		    t[k] = props.bgsx.fields[k].name;
            		}
            		let expectedFields = Object.keys(tempjson.value[0]);
            	    expectedFields = expectedFields.filter(item => item !== 'Cjz'); //cjz不检测
                    if (JSON.stringify(Object.values(t)) !== JSON.stringify(expectedFields)) {
                        const importedFields = Object.values(t);
                        const missingFields = expectedFields.filter(field => !importedFields.includes(field));
                        const extraFields = importedFields.filter(field => !expectedFields.includes(field));
                        if (missingFields.length > 0) {
                            return ElMessage.error(`导入表格多出列：${missingFields.join(', ')}`);
                        } else if (extraFields.length > 0) {
                            return ElMessage.error(`导入表格缺少列：${extraFields.join(', ')}`);
                        } else {
                            return ElMessage.error('导入表格第一行不正确');
                        }
                    }
        			if(drjy.value){
        			    for (const value of tempjson.value) {
                            let fh = jysj(value, props.bgsx.fields);  //校验数据
                            if (fh.code == 1){
                                tzpagerow(fh.data); //跳转相应页并选中此行
                                return ElMessage.error(fh.msg);
                            }
        			    }
        			}
        			insertdata(props.bgsx.tablename);
        	    }
            };
            
            //校验数据
            const jysj = (data, fields) => {
                if(!fields || Object.keys(fields).length == 0){
                    return {msg:'字段或设置为空', code:1};
                }
                let i = 0;
                for(let k in fields){
                    let zdm = fields[k].name
                    if(fields[k].required){
                        //校验必填
                        if(!data[zdm]){
                            return {msg: zdm + '不得为空', code: 1, data: data};
                        }else{
                            let lx = fields[k].type;//字段类型
                            if(lx == 'select' || lx == 'radio'){
                                let xx = fields[k].options ? fields[k].options.split('/') : '';
                                if(!xx || xx.length < 1){
                                    return {msg: zdm+'字段的选项设置错误', code: 1, data: data};
                                }else if(!xx.includes(data[zdm])){
                                    return {msg: data[zdm]+'填写不正确，填写范围：'+xx, code: 1, data: data};
                                }
                            }else if(lx == 'number' && Math.floor(Number(data[zdm])) !== Number(data[zdm])){
                                //校验整数
                                return {msg: data[zdm]+'必须是整数', code: 1, data: data};
                            }else if(lx == 'mobile' && !validators.isMobile(data[zdm])){
                                //校验手机号
                                return {msg: data[zdm]+'必须是手机号', code: 1, data: data};
                            }else if(lx == 'idcard' && validators.isIdcard(data[zdm]) !== true){
                                //校验身份证号
                                return {msg: data[zdm] + '：' + validators.isIdcard(data[zdm]), code: 1, data: data};
                            }
                        }
                    }
                }
                return {msg:'校验通过', code:0, data: data};
            }
    
            // 数据导入
            const insertdata = async (tableName) => {
                qdloading.value = true;
                const BATCH_SIZE = 600
                let currentBatch = []
                let processedCount = 0
                for (const item of tempjson.value) {
                    processedCount++
                    currentBatch.push(processDataItem(item))
                    if (currentBatch.length >= BATCH_SIZE) {
                        await sendBatchData(tableName, currentBatch)
                        currentBatch = []
                    }
                    updateProgress(processedCount)
                }
                if (currentBatch.length > 0) {
                    await sendBatchData(tableName, currentBatch)
                }
                qdloading.value = false;
                ElMessage.success('数据导入完成');
                setTimeout(() => {
        			closeDialog();
        			emit('update-success'); // 触发父组件更新
        		}, 500);
            }
    
			const processDataItem = (rawItem) => {
				return Object.entries(newbgsx.value.fields).reduce((item, [fieldKey, config]) => {
					item[fieldKey] = String(rawItem[config.name] || '');
					return item;
				}, {});
			}
    
            const updateProgress = (processed) => {
                pageState.value.percent = Math.min(99, Math.floor((processed / pageState.value.total) * 100));
            }
    
            const sendBatchData = async (tableName, data) => {
                await tablepost({ tablename: tableName, data });
            }
            
            //关闭弹窗
			const closeDialog = () => {
			    //upload.value.clearFiles();//清空文件选择器
			    resetUploadState();
                emit('update:dialog-visible', false); // 通知父组件更新状态
            };
            
            // 下载模板
            const downloadTemplate = () => {
                let headers = {};
                for (let k in newbgsx.value.fields) {
                    headers[k] = newbgsx.value.fields[k].name;
                }
                let templateData = [];
                exportToExcel(newbgsx.value.tablename + '.xlsx', templateData, headers); 
            }
            
            //跳转对应页和行，并打开编辑
            const tzpagerow = (row) => {
                const { pageSize } = pageState.value;
                singleTable.value.setCurrentRow(row);//选中行
                row.isEdit = true;//编辑状态
                let mypage = Math.trunc(row.__rowNum__ / pageSize) + 1;
                pageState.value.page = mypage > 1 ? mypage : 1;
            }

            //翻页
            const handleCurrentChange = (val) => {
                pageState.value.page = val;
            }
        
            //每页数量改变
            const sizechange = (e) => {
                pageState.value.pageSize = e;
            }
        	
        	//编辑保存
            const handleClick = (row) => {
                if (row.isEdit) {
                    delete row.isEdit;
                    emit('getexcel', {data: tempjson.value, lx: props.lx});//传递给父组件
                } else {
                    row.isEdit = true;
                }
            }

			return {
			    jysj,
			    singleTable,
			    qdloading,
			    submitDrsj,
			    isImageUrl: window.validators.isImageUrl,
			    drjy,
			    tzpagerow,
			    handleCurrentChange,
			    sizechange,
			    handleClick,
			    insertdata,
				tempjson,
				pageState,
				fieldsConfig,
				upload,
				handleFileChange,
				readExcelFile,
				readImages,
				processFile,
				extractRelativePath,
				extractIDFromFormula,
				isSpecialEmpty,
				processImportedData,
				beforeUpload,
				newbgsx,
                getcolumns,
                gettempdata,
                closeDialog,
                downloadTemplate
			};
		},
        
    template: `
    <div class="readxlsx">
        <el-form-item label="校验数据" prop="drjy">
            <el-tooltip v-if="bgsx" content="开启后，将校验每行数据的：必填、手机号、身份证号、选项范围等。">
                <el-switch v-model="drjy"></el-switch>
            </el-tooltip>
        </el-form-item>
        
        <p style="color:#A8ABB2;">表格第一行必须现在数据相同，请下载模板来导入:
            <el-button type="primary" link @click="downloadTemplate()">下载模板</el-button>&nbsp;
        </p>
        
        <el-form-item label="上传表格" prop="file" style="width:100%" v-if="pageState.total == 0" label-position="top">
            <el-upload ref="upload" style="width:100%" drag action="#" :auto-upload="false" :limit="1" :on-change="handleFileChange" :before-upload="beforeUpload" accept=".xlsx">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">拖拽文件至此区域或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip">请上传xlsx格式的表格文件</div>
                </template>
            </el-upload>
        </el-form-item>
        
        <div v-if="pageState.total > 0" style="width:100%">
		    <div style="width:100%;margin-top:-5px;">
        		<span><b style="color:blue;">表格共有{{ pageState.total }}行数据</b></span>
        		<el-table ref="singleTable" v-if="pageState.total > 0" :data="tempjson.slice((pageState.page - 1) * pageState.pageSize, pageState.page * pageState.pageSize)" style="margin-top:10px;" border :header-cell-style="{'font-size': '14px'}"  show-overflow-tooltip :row-style="{'font-size':'14px'}">
                    <el-table-column width="60" label="序号" type="index" >
                        <template #default="scope">
                            <!--<span>{{(pageState.page-1)*pageState.pageSize + scope.$index+1}}</span>-->
                            <span>{{ scope.row.__rowNum__ }}</span>
                        </template>
                    </el-table-column>
        			<template v-for="(v, k) in tempjson[0]">
                        <el-table-column :prop="k" :label="k" v-if="k != 'isEdit'">
                            <template #default="scope">
                                <div v-if="!scope.row.isEdit">
                                    <img v-if="isImageUrl(scope.row[k])" :src="scope.row[k]" style="width:50px;height:50px;" />
                                    <span v-else>{{ scope.row[k] }}</span>
                                  </div>
                                <div v-else>
                                	<el-input class="birthday" v-model="scope.row[k]"></el-input>
                                </div>
                            </template>
                        </el-table-column>
        			</template>
        
        			<el-table-column label="操作">
        				<template #default="scope">
        					<el-button v-on:click="handleClick(scope.row)">{{ scope.row.isEdit ? '完成' : '编辑' }}</el-button>
        				</template>
        			</el-table-column>
        		</el-table>
        		<el-pagination hide-on-single-page background @size-change="sizechange" :page-sizes="[10, 20, 30, 50]" :page-size="pageState.pageSize" :current-page.sync="pageState.page" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper" :total="pageState.total"></el-pagination>
		    </div>
            
            <div v-if="pageState.percent > 0" class="progress-container">
                <div class="progress-info">
                    <span>导入进度：{{ pageState.percent }}%</span>
                    <span>{{ pageState.percent === 100 ? '导入完成' : '正在导入...' }}</span>
                </div>
                <div class="progress-bar">
                    <div class="progress-inner" :style="{ width: pageState.percent + '%' }"></div>
                </div>
            </div>
        </div>
        
        <el-row justify="center">
            <el-col :span="8" style="text-align: center;margin: 20px;">
                <el-button type="primary" :loading="qdloading" v-if="newbgsx.formname && pageState.total > 0" size="large" style="margin-right:20px" @click="submitDrsj()">提交</el-button>
                <el-button @click="closeDialog()" size="large">取消</el-button>
            </el-col>
		</el-row>
    </div>
    `
}